import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:safetymonitor/app/components/custom_app_bar.dart';
import 'package:safetymonitor/app/components/custom_modele/custom_title_chart_page.dart';
import 'package:safetymonitor/app/core/core.dart';
import 'package:safetymonitor/app/core/http/http.dart';
import 'package:safetymonitor/app/core/utils/interface.dart';
import 'package:safetymonitor/app/data/entities/application/device_location_entity.dart';
import 'package:safetymonitor/app/data/entities/application/get_device_info_entity.dart';
import 'package:safetymonitor/app/data/entities/application/plotting_base_entity.dart';

import 'package:safetymonitor/generated/assets.dart';

/// 设备详情
class DeviceDetails extends StatefulWidget {
  const DeviceDetails({super.key});

  @override
  State<DeviceDetails> createState() => _DeviceDetailsState();
}

class _DeviceDetailsState extends State<DeviceDetails> {
  final GetDeviceInfoEntity _deviceInfo = Get.arguments as GetDeviceInfoEntity;
  URLRequest? url;
  InAppWebViewController? inAppWebViewController;
  DeviceLocationEntity? deviceLocationEntity;
  @override
  void initState() {
    //批量获取标绘信息列表
    _getPlottingJsonData();
    // url = URLRequest(url: WebUri('http://192.168.50.131:30012/#/nest?func=3dDisplay&_t=1712826013832&scale=0'));
       url = URLRequest(url: WebUri('${Interface.plotMapAddress}/#/nest?func=3dDisplay&_t=1712826013832&scale=0'));
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFF7FBFE),
      appBar: CustomAppBar(
        leading: IconButton(icon: const Icon(Icons.arrow_back_ios_new), iconSize: 24.w, color: const Color(0xFFFFFFFF), onPressed: Get.back),
        title: Text(
          '详情',
          style: TextStyle(
            fontWeight: FontWeight.w400,
            color: const Color(0xFFFFFFFF),
            fontSize: 16.sp,
          ),
        ),
        backgroundColor: const Color(0xFF0462DC),
      ),
      body: Stack(
        children: [
          Container(
            alignment: Alignment.center,
            height: 102.w,
            color: const Color(0xFF0462DC),
          ),
          Container(
            padding: EdgeInsets.symmetric(horizontal: 16.w),
            child: SingleChildScrollView(
              child: Column(
                children: [
                  AppGaps.vGap16,
                  CustomTitleChartPage(
                    contentPadding: EdgeInsets.only(right: 16.w, left: 16.w, top: 16.w),
                    title: '${_deviceInfo.deviceName}',
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Row(
                          children: [
                            Expanded(child: _getTextView(title: '设备类型:', value: '${_deviceInfo.deviceTypeName}')),
                            Expanded(child: _getTextView(title: '设备等级:', value: '${_deviceInfo.deviceLevelName}')),
                          ],
                        ),
                        Row(
                          children: [
                            Expanded(child: _getTextView(title: '是否投用:', value: _deviceInfo.isUse == 1 ? '是' : '否')),
                            Expanded(child: _getTextView(title: '设备编码:', value: '${_deviceInfo.deviceCode}')),
                          ],
                        ),
                        Row(
                          children: [
                            Expanded(child: _getTextView(title: '经度:', value: '${_deviceInfo.longitude}')),
                            Expanded(child: _getTextView(title: '纬度:', value: '${_deviceInfo.latitude}')),
                          ],
                        ),

                        Row(
                          children: [
                            Expanded(child: _getTextView(title: '设备归属:', value: '${_deviceInfo.companyName?.trim()}')),
                            Expanded(child: _getTextView(title: '高程(海拔高度)', value: '${_deviceInfo.altitude}')),
                          ],
                        ),
                      ],
                    ),
                  ),
                  AppGaps.vGap16,
                  // Container(
                  //   width: double.infinity,
                  //   height: 200,
                  //   decoration: BoxDecoration(
                  //     color: Colors.white,
                  //     borderRadius: BorderRadius.circular(10.w),
                  //   ),
                  //   child: Center(child: Text('地图')),
                  // ),

                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 状态显示
  Widget _getStatueView() {
    return SizedBox(
      child: Stack(
        alignment: Alignment.centerRight,
        children: [
          SvgPicture.asset(
            Assets.svgBgStatue,
            fit: BoxFit.cover,
          ),
          Text(
            '未处置',
            style: TextStyle(
              fontSize: 14.sp,
              height: 1.2,
              fontWeight: FontWeight.w400,
              color: const Color(0xFF3F425B),
            ),
          ),
        ],
      ),
    );
  }

  /// 获取字段显示
  Widget _getTextView({required String title, required String value}) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              title,
              style: TextStyle(
                fontSize: 14.sp,
                height: 1.2,
                fontWeight: FontWeight.w400,
                color: const Color(0xffC7CEE5),
              ),
            ),
            AppGaps.hGap6,
            Expanded(
                child: Text(
              value,
              style: TextStyle(
                fontSize: 14.sp,
                height: 1.2,
                fontWeight: FontWeight.w400,
                color: const Color(0xff1D3452),
              ),
            ))
          ],
        ),
        AppGaps.vGap10,
      ],
    );
  }

  /// webview加载完成后
  onWebViewCreated(InAppWebViewController controller) async {
    inAppWebViewController = controller;
    // 先加载地形
    await _loadTerrain('http://203.25.217.225:38080/model/SCDiXing/yibin');
    // 加载瓦片
    await _loadTileset('http://203.25.217.39:81/model/SiChuan/YiBin/P-YB003/tileset.json');
    // 数据初始化
    await _postData();
    //元素定位
    await _dataFlyTo();
  }

  // 加载地形地址
  _loadTerrain(String url) async {
    final data = {
      'type': 'Terrain',
      'data': {
        'url': url,
      }
    };
    await Future.delayed(const Duration(seconds: 2));
    _sendMessage(data);
  }

  /// 加载瓦片地址
  _loadTileset(String tilesetUrl) async {
    final data = {
      'type': 'Tileset',
      'data': {
        'url': tilesetUrl,
      }
    };
    await Future.delayed(const Duration(seconds: 2));
    _sendMessage(data);
  }

  /// 数据初始化
  _postData() async {
    final data = {
      'type': 'DataInit',
      'data': {
        'group': 'default',
        'data': [
          // {
          //   'id': 'DeviceLocation_68',
          //   'mode': 'Pin',
          //   'name': '图标点',
          //   'type': 'Pin',
          //   'UIMode': '',
          //   'options': {},
          //   'positions': [1.8347159012635197, 0.5012867854364944, 294.2381357137446]
          // },
          {
            'id': deviceLocationEntity?.id,
            'mode': deviceLocationEntity?.mode,
            'name': deviceLocationEntity?.name,
            'type': deviceLocationEntity?.type,
            'UIMode': deviceLocationEntity?.uiMode,
            'options': deviceLocationEntity?.options,
            'positions': deviceLocationEntity?.positions
          },
        ]
      }
    };
    await Future.delayed(const Duration(seconds: 2));
    _sendMessage(data);
  }

  /// 发送消息
  Future<void> _sendMessage(data) async {
    print('_sendMessage：${jsonEncode(data)}');
    await inAppWebViewController?.postWebMessage(message: WebMessage(data: jsonEncode(data)));
  }

  /// 元素定位
  _dataFlyTo() async {
    final data = {
      'type': 'DataFlyTo',
      'data': {
        // 'key': 'bbcd1238-aacc-3652-56ad-205ccfe25ad36df1',
        // 'key': 'DeviceLocation_68',
        // 'key': 'DeviceLocation_${_deviceInfo.id}',
        'key': deviceLocationEntity?.id,
      }
    };
    await Future.delayed(const Duration(seconds: 2));
    _sendMessage(data);
  }

  ///批量获取标绘信息列表
  void _getPlottingJsonData() async {
    final res = await HttpUtil().generatePostRequest<List<PlottingBaseEntity>>(
      Interface.getPlottingJsonData,
      data: ['DeviceLocation_${_deviceInfo.id}'],
    ).execute(
      isShowLoading: false,
      isShowToast: false,
    );
    res.onSuccess((result) async {
      if (result.data != null) {
        if (result.data!.isNotEmpty && result.data!.first.jsonDate.isNotEmpty) {
          //将Json String转换为Map
          // final Map<String, dynamic> jsonEncod = jsonDecode(result.data!.first.jsonDate) as Map<String, dynamic>;
          //将map 转换为实体对象
          deviceLocationEntity = DeviceLocationEntity.fromRawJson(result.data!.first.jsonDate);
        }
      }
    });
  }
}
